﻿using DevExpress.XtraEditors;
using Rimifier.Properties;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.Linq;

namespace Rimifier.Support
{
	public class UtilityFunctions
	{
		public static string AssemblyTitle
		{
			get
			{
				var attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
				if (attributes.Length > 0)
				{
					var titleAttribute = (AssemblyTitleAttribute)attributes[0];
					if (titleAttribute.Title != "")
					{
						return titleAttribute.Title;
					}
				}
				return Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
			}
		}

		public static Boolean CheckFileExistance()
		{
			if (!File.Exists(Settings.Default.SelectedSaveFilePath))
			{
				// We are NOT good to load
				XtraMessageBox.Show("There is no save file selected to load.", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
				return false;
			}
			return true;
		}

		public static List<XElement> GetMainSaveFileAsList(String requiredSection = "")
		{
			if (!CheckFileExistance())
			{
				return null;
			}
			var xmlDocument = XDocument.Load(Settings.Default.SelectedSaveFilePath);
			var xmlList = xmlDocument.Descendants().ToList();
			if (!String.IsNullOrEmpty(requiredSection))
			{
				return xmlList.Where(where => where.Name == requiredSection).ToList();
			}
	
				return xmlList;
		}

		public static XDocument GetMainSaveFileAsXml()
		{
			if (!CheckFileExistance())
			{
				return null;
			}
			return XDocument.Load(Settings.Default.SelectedSaveFilePath);
		}

		public static XElement GetMainSaveFileAsElement()
		{
			if (!CheckFileExistance())
			{
				return null;
			}
			return XElement.Load(Settings.Default.SelectedSaveFilePath);
		}

		public static void BackupSaveFile(string sourceEdit)
		{
			if (!Directory.Exists(Settings.Default.BackupSaveFilePath))
			{
				Directory.CreateDirectory(Settings.Default.BackupSaveFilePath);
			}

			var currentSaveFile = GetMainSaveFileAsXml();
			var backupName = Settings.Default.SelectedSaveFilePath.Replace(".rim", String.Format(".before.{0}.{1}.rim", sourceEdit, DateTime.Now.ToOADate()));

			currentSaveFile.Save(Settings.Default.BackupSaveFilePath + Path.GetFileName(backupName));

		}

		public static int GetColorValue(string match)
		{
			return (int)Math.Round(double.Parse(match, CultureInfo.InvariantCulture) * 255);
		}

		public static Int32 ControlledNewId(List<Int32> disallowed, Int32 min, Int32 max)
		{
			var generated = 0;
			var conditionMet = false;
			while (!conditionMet)
			{
				generated = RandomHelper.Instance.Next(100000, 999999);
				if (disallowed.Any() && !disallowed.Contains(generated))
				{
					conditionMet = true;
				}
			}
			return generated;
		}

	}
}